package zhang.lao.service.sequence;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import zhang.lao.build.mybatis.jdbc.auto.model.SysSequence;
import zhang.lao.build.mybatis.jdbc.auto.model.SysSequenceExample;
import zhang.lao.build.tool.ListUtils;
import zhang.lao.dao.base.SysSequenceDao;

import java.util.List;

/**
 * Created by Administrator on 2018/1/28.
 */
@Component
public class SequenceTool {

    @Autowired
    private SysSequenceDao sysSequenceDao;
   public int getSequence(String key){
       SysSequenceExample sysSequenceExample = new SysSequenceExample();
       sysSequenceExample.createCriteria().andBelongBoEqualTo(key);
       List<SysSequence> sysSequences = sysSequenceDao.selectByExample(sysSequenceExample);
       SysSequence first = ListUtils.getFirst(sysSequences);
       if(first!=null){
           first.setNumber(first.getNumber()+1);
           sysSequenceDao.updateByPrimaryKey(first);
           return first.getNumber();
       }else{
           first = new SysSequence();
           first.setBelongBo(key);
           first.setNumber(1);
           sysSequenceDao.insertSelective(first);
           return 1;
       }

   }
    public int getSequence(String key,int start){
        SysSequenceExample sysSequenceExample = new SysSequenceExample();
        sysSequenceExample.createCriteria().andBelongBoEqualTo(key);
        List<SysSequence> sysSequences = sysSequenceDao.selectByExample(sysSequenceExample);
        SysSequence first = ListUtils.getFirst(sysSequences);
        if(first!=null){
            first.setNumber(first.getNumber()+1);
            sysSequenceDao.updateByPrimaryKey(first);
            return first.getNumber();
        }else{
            first = new SysSequence();
            first.setBelongBo(key);
            first.setNumber(start);
            sysSequenceDao.insertSelective(first);
            return start;
        }
    }
}
